#!/bin/bash
#################################################################
#\brief help run c/c++ file
#\example dcsh hello.cpp "hello world"
#         do: 1. compile hello.cpp 
#             2. launch hello.exe "hello world"
#
################################################################
############# function ###################################################
printhelp(){
    echo "dcsh shell_file_name"
    echo "for example:"
    echo "  dcsh file.cpp"
    echo "  dcsh file.c"
}
############# function ###################################################
shellfile=$1               #/home/ab/cd/ec.cpp
#echo "$shellfile"
if [ $# = 0 ]; then
    printhelp
    exit 0 
fi
shift
args=$@
#echo $args

if [ ! -e ${DCSH_PATH}/makefile.inc ]; then
    DCSH_PATH=~/googlecode/codelibrarydzh/include
fi

if [ ! -e $shellfile ]; then
    echo "$shellfile: No such file or directory"
    exit 0
fi

shellpath=$(dirname $shellfile)        #/home/ab/cd/
#echo "shellpath: $shellpath"
shellbase=$(basename $shellfile)       #ec.cpp 
#echo "$shellbase"

shellbaseprefix=${shellbase%.*}        #ec
#echo "$shellbaseprefix"

shellbasesuffix=${shellbase##*.}        #ec
#echo "$shellbasesuffix"
if [ "$shellbasesuffix" != "cpp" ] && [ "$shellbasesuffix" != "c" ]; then
    echo "dcsh can only parse c source file"
    exit 0
fi

exebase=${shellbaseprefix}.exe         #ec.exe
#echo $exebase

exefile=${shellpath}/release/${exebase} #/home/ab/cd/release/ec.exe
#echo $exefile

logfile=${shellpath}/.${shellbaseprefix}.log

requirelist=`awk -F "[\"<>]" '/\/\/!require/{printf("%s ", $2)}' $shellfile` 
requiresrcfile=`echo $requirelist | awk '{for(i=1;i<=NF;i++) { if($i ~ /\.c(pp)?$/)printf("%s ", $i)}}'`  
sourcefile="$requiresrcfile $shellbase"
inc_path=`echo $requirelist | awk '{for(i=1;i<=NF;i++) { if($i ~ /.*\/$/)printf("%s ", $i)}}'`
ext_lib=`echo $requirelist | awk '{for(i=1;i<=NF;i++) { if(($i !~ /\.c(pp)?$/)&&($i !~ /.*\/$/))printf("%s ", $i)}}'`

make -C  $shellpath -f ${DCSH_PATH}/makefile.inc ext_inc="${DCSH_PATH} ${inc_path}" ext_lib="${ext_lib}" ext_libpath="${inc_path}" SOURCEFILE="${sourcefile}" EXECUTABLE="$exebase"  &> $logfile
buildres=`grep -E "(make: .*Error |make: \*\*\* No rule to make target)" $logfile`
if [ ! -z "$buildres" ]; then
    colormakeexist=`which colormake.pl`
    if [ -z "$colormakeexist" ]; then
        cat $logfile
    else
        cat $logfile | colormake.pl 
    fi
    exit 1
fi

#rm -f $logfile
$exefile $args
